<template>
  <div>
    <div
      class="ant-input tag-box"
      :class="{ backgroundColor: disabled }"
      tabindex="0"
      @click="openModal"
      v-if="whetherShow"
    >
      <div class="prompt-box">
        <template v-if="userList.length">
          <a-tag
            v-for="(item, index) in userList"
            :key="item.uuid"
            closable
            @close="() => handleTagClose(item[valueField || 'userNameId'])"
          >
            {{ item.userName }}/{{ item.userNameId }}
          </a-tag>
        </template>
        <div v-else>{{ placeholder }}</div>
      </div>
    </div>
    <personnel-popup-modal
      ref="personnelPopup"
      treeText="text"
      :visible="visible"
      :multiple="multiple"
      :dataList="dataList"
      :rawTreeData="treeData"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    ></personnel-popup-modal>
  </div>
</template>
<script>
import PersonnelPopupModal from "./modal/PersonnelPopupModal.vue";
export default {
  components: {
    PersonnelPopupModal,
  },
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    value: "",
    whetherShow: {
      type: Boolean,
      default: true,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    url: {
      type: String,
      // default: "/mdata/organization/getTreeSysOrganization",
      default: "/mdata/organization/getTreeOrganizationAndUserData",
    },
    placeholder: {
      type: String,
      default: "请选择人员",
    },
    valueField: {
      type: String, // 保存的字段，可选uuid,userNameId
      default: "userNameId",
    },
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler: function(e) {
        if (!e) {
          this.userList = [];
        } else {
          this.getUserDetail();
        }
      },
    },
  },
  data() {
    return {
      userList: [],
      treeData: [],
      dataList: [],
      visible: false,
    };
  },
  mounted() {
    this.userList = [];
  },
  methods: {
    getTreeData() {
      this.$post(this.url).then((res) => {
        if (res.statusCode === 200) {
          this.dataList = [];
          this.treeData = res.data;
          this.recursiveTree(this.treeData);
          this.generateList(this.treeData);
          this.visible = true;
          this.userList.forEach((item) => {
            item.userNameAndId = item.userName + "/" + item.userNameId;
          });
          this.$refs.personnelPopup.selectData = this.userList;
        }
      });
    },
    recursiveTree(data) {
      data.forEach((e) => {
        if (e.orgName) {
          e.text = e.orgName;
        }
        if (e.children.length > 0) {
          this.recursiveTree(e.children);
        }
        if (e.list) {
          if (e.list.length > 0) {
            let list = [];
            e.list.forEach((l) => {
              list.push({
                id: l.userNameId,
                text: l.userName + "/" + l.userNameId,
                userName: l.userName,
                orgId: l.orgId,
                uuid: l.uuid,
                user: true,
              });
            });
            e.children = e.children.concat(list);
          }
        }
      });
    },
    getUserDetail() {
      if (this.value) {
        let valueField = this.valueField || "userNameId";
        this.$post("/mdata/user/getUserDetailById", {
          ids: this.value,
          fieldName: valueField,
        }).then((res) => {
          if (res.statusCode === 200) {
            this.userList = res.data;
            // this.$emit("change", this.userList.map(e => e[valueField]).toString(), this.userList)
          } else {
            this.$message.error(res.message, 1.5);
          }
        });
      }
    },
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        if (node?.children?.length > 0 || node?.orgName) {
          this.dataList.push({
            key: node.id,
            title: node.text,
            icon: "apartment",
            // icon: node.iconCls
          });
          node.slots = { icon: node.id.toString() };
          this.generateList(node.children);
        } else {
          node.slots = { icon: node.id.toString() };
          this.dataList.push({
            key: node.id,
            title: node.text,
            icon: "user",
            // icon: node.iconCls
          });
        }
      }
    },
    openModal() {
      if (!this.disabled) {
        this.getTreeData();
      }
    },
    handleConfirm(data) {
      let valueField = this.valueField || "userNameId";
      this.visible = false;
      this.userList = data;
      this.$emit("change", data.map((e) => e[valueField]).toString(), data);
    },
    handleCancel() {
      this.visible = false;
      this.userList = [];
      this.$emit("close");
    },
    handleTagClose(value) {
      let valueField = this.valueField || "userNameId";
      const data = this.userList.filter((item) => item[valueField] !== value);
      this.$emit("change", data.map((e) => e[valueField]).toString(), data);
      this.userList = data;
    },
  },
};
</script>
<style lang="less" scoped="scoped">
.backgroundColor {
  background-color: #f5f5f5;
}
.tag-box {
  cursor: pointer;
  height: auto;
  padding: 0 4px 4px;
  .prompt-box {
    line-height: 22px;
    div {
      display: inline-block;
      margin-top: 4px;
      margin-left: 5px;
      color: #bfbfbf;
      overflow-wrap: anywhere;
    }
    .ant-tag {
      margin-top: 4px;
    }
  }
}
</style>
